package com.wuyou.mid;


import java.util.Arrays;

/**
 * @Description 2336. 无限集中的最小数字
 * @Author yh.zhang
 * @Date 2023/11/29 10:36
 */
public class SmallestInfiniteSet {

    int[] nums;
    int size;

    TreeNode head;

    public SmallestInfiniteSet() {
        this.nums = new int[1000];
        Arrays.fill(nums, 1);
        this.size = 1000;
        head = new TreeNode(0);
        TreeNode cur = head;
        for (int i = 1; i <= 1000; i++) {
            TreeNode next = new TreeNode(i);
            cur.next = next;
            cur = next;
        }
    }

    public int popSmallest() {
        if (this.isEmpty()) {
            return -1;
        }
        TreeNode cur = head.next;
        head.next = cur.next;
        this.nums[cur.val - 1] = 0;
        this.size--;
        System.out.println("popSmallest---head = " + this.head.val);
        return cur.val;
    }

    public void addBack(int num) {
        if (nums[num - 1] == 1) {
            return;
        }
        TreeNode cur = new TreeNode(num);
        if (this.size == 0) {
            head.next = cur;
            this.nums[num-1] = 1;
        } else {
            TreeNode temp = head;
            while (temp != null && temp.next != null) {
                if (temp.val < num && temp.next.val > num) {
                    break;
                }
                temp = temp.next;
            }
            TreeNode tempNext = temp.next;
            temp.next = cur;
            cur.next = tempNext;
            // System.out.println("addBack---temp = " + temp.val);
            // System.out.println("addBack---temp = " + temp.next.val);
            // System.out.println("addBack---temp = " + temp.next.next.val);
        }
        this.size++;
        this.nums[num - 1] = 1;
        System.out.println("addBack---head = " + this.head.val);
    }

    private boolean isEmpty() {
        return this.size == 0 || this.nums == null;
    }

    class TreeNode {
        int val;
        TreeNode pre;
        TreeNode next;

        public TreeNode(int val) {
            this.val = val;
        }
    }
}

